package cn.itsource.basic.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.org.vo.UserInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class GetUserInfoUtil {

    /**
     * 获取user_id
     */
    public static Long getUserId(){
        return getUserInfo().getId();
    }

    /**
     * 获取店铺id
     * @return
     */
    public static Long getShopId(){
        Long shopId = getUserInfo().getShopId();
        Optional.ofNullable(shopId).orElseThrow(() -> new BusinessException("你的账号没有店铺id,请和管理员确认"));

        return getUserInfo().getShopId();
    }


    /**
     * 获取redis里面的UserInfo信息
     * @return
     */
    public static UserInfo getUserInfo(){
        //1.从request对象获取token
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //1.1获取request
        String token = request.getHeader("token");

        //1.2获取token
        //2.通过token拿到redis里面的信息,如果拿不到,同样让他去登录
        //通过工具获取redisService
        RedisService redisService = SpringUtil.getBean(RedisService.class);

        //1.3从redis里面获取UserInfo
        UserInfo userInfo = redisService.getKeyObjectValue(token, UserInfo.class);

        return Optional.ofNullable(userInfo).orElseThrow(() -> new BusinessException("登录失效,重新登录"));
    }


}
